package com.taotao.job.rpc.core.proxy;

import com.taotao.job.rpc.core.invoker.Invoker;
import com.taotao.job.rpc.core.invoker.InvokerMeta;
import com.taotao.job.rpc.core.meta.IfaceMeta;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author fanbeibei
 * @date 2020/10/31 0:30
 */
public class JdkRpcProxyFactory extends AbstractRpcProxyFactory {

    @Override
    public <T> T newProxyInstance0(Class<T> ifaceClass, Invoker invoker) {
        if (!ifaceClass.isInterface()) {
            throw new UnsupportedOperationException("JdkRpcProxyFactory support only interface!");
        }

        return (T) Proxy.newProxyInstance(JdkRpcProxyFactory.class.getClassLoader(), new Class<?>[]{ifaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return invoker.invokeMethod(new InvokerMeta(new IfaceMeta(ifaceClass.getName(), method.getName()), args), method.getReturnType());
            }
        });
    }
}
